package database;

import hypeerweb.HyPeerWeb;
import hypeerweb.Node;
import hypeerweb.NodeDelegate;
import hypeerweb.NodeProxy;

import java.util.ArrayList;

/**
 * The database of node proxies that the nodes in this segment of the hypeerweb
 * are related to. 
 * 
 * 
 * @author brinkerhoff_kendra
 */
public class NodeProxyDB {
	private static NodeProxyDB singleton;
	private ArrayList<NodeProxy> nodeProxies;
	
	private NodeProxyDB() {
		nodeProxies = new ArrayList<NodeProxy>();
	}
	
	private NodeProxyDB(Node node) {
		nodeProxies = new ArrayList<NodeProxy>();
		ArrayList<NodeDelegate> nodes = node.getConnections().getAllConnections();
		addNodeDelegates(nodes);
	}
	
	public static NodeProxyDB getSingleton() {
		if(singleton == null) {
			singleton = new NodeProxyDB();
		}
		return singleton;
	}
	
	private void addNodeDelegates(ArrayList<NodeDelegate> nodes) {
		for(NodeDelegate n : nodes) {
			if(n != null && n.getDelegate() != null) {
				addNode(n.getDelegate());
			}
		}
	}
	private boolean checkIfExists(Node node){
		for(NodeProxy np: nodeProxies){
			if(np.getWebId().getValue()==node.getWebId().getValue())
				return true;
		}
		return false;
	}
	private void addNode(Node node) {
		if(node == null || !(node instanceof NodeProxy)) {
			return;
		}

		if(!checkIfExists(node)) {
			nodeProxies.add((NodeProxy)node);
		}
	}
	
	public ArrayList<NodeProxy> getAllNodeProxies() {
		nodeProxies.clear();
		ArrayList<Integer> nodeInts = HyPeerWeb.getSingleton().getNodesInSegment();
		for(Integer i : nodeInts) {
			Node n = HyPeerWeb.getSingleton().getNode(i);
			ArrayList<NodeDelegate> nodes = n.getConnections().getAllConnections();
			addNodeDelegates(nodes);
		}
		
		return nodeProxies;
	}
	
	public static ArrayList<NodeProxy> getNodeProxies(Node node) {
		NodeProxyDB db = new NodeProxyDB(node);
		return db.nodeProxies;
	}
	
	public String toString() {
		//getAllNodeProxies();
		String result = "Node Proxies:\n";
		/*for(Node n : nodeProxies) {
			result += "\t" + n + "\n";
		}*/
		return result;
	}
}
